<template>
  <!-- 新增活动 -->
  <el-dialog
    v-model="visible"
    :title="form.shopGroupWorkId ? visitDetail ? '查看拼团活动' : '修改拼团活动' : '新增拼团活动'"
    class="addGroupBuy"
    width="700px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @close="close"
  >
    <div class="addGroupBuyBox">
      <el-form
        ref="formRef"
        class="formBox"
        :model="form"
        label-width="150px"
        :rules="rules"
        :disabled="visitDetail"
      >
        <el-form-item label="活动名称" prop="groupName">
          <el-input
            v-model="form.groupName"
            maxlength="15"
            placeholder="请输入活动名称"
            oninput="value=value.replace(/\s+/g, '')"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            maxlength="200"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="拼团使用时间" prop="activityDate">
          <el-date-picker
            v-model="dateInfo"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="成团人数" prop="person">
          <el-input
            v-model="form.person"
            maxlength="9"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px;"
          />&nbsp;人
        </el-form-item>
        <el-form-item label="成团有效时间" prop="effectiveTime">
          <el-input
            v-model="form.effectiveTime"
            maxlength="9"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px;"
          />&nbsp;小时
        </el-form-item>
        <el-form-item label="商品限购" prop="ifLimit">
          <el-radio-group v-model="form.ifLimit">
            <el-radio :label="1">不限购</el-radio>
            <el-radio :label="2">限购</el-radio>
          </el-radio-group>
          <el-input
            v-model="form.limitNumber"
            maxlength="9"
            :disabled="form.ifLimit === 1"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px;"
          />&nbsp;件/人
        </el-form-item>
        <el-form-item label="活动预热" prop="ifEnable">
          <el-radio-group v-model="form.ifEnable">
            <el-radio :label="1">停用</el-radio>
            <el-radio :label="2">启用</el-radio>
          </el-radio-group>
          <el-input
            v-model="form.enableTime"
            maxlength="9"
            :disabled="form.ifEnable === 1"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px;"
          />&nbsp;小时前
        </el-form-item>
        <el-form-item label="优惠券叠加" prop="overlying">
          <el-radio-group v-model="form.ifAdd">
            <el-radio :label="1">叠加</el-radio>
            <el-radio :label="0">不叠加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="applyType" label="活动商品" prop="commodity">
          <span
            class="selectBtn"
            @click="chooseProduct"
          >
            <span v-if="!visitDetail">请选择</span>
            <span v-else>查看商品</span><i v-if="form.details.length !== 0" class="selectNum">{{
              form.details.length
            }}</i></span>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button
        v-show="!visitDetail"
        type="primary"
        @click="addGroupBuyFn"
      >保 存</el-button>
      <el-button
        v-if="visitDetail"
        type="primary"
        @click="goToGroupBuy"
      >取 消</el-button>
      <el-button v-else type="danger" @click="goToGroupBuy">取 消</el-button>
    </span>
    <!-- 新建分组弹框 -->
    <el-dialog
      v-model="productVisible"
      :title="visitDetail ? '查看商品' : '选择商品'"
      width="55%"
      top="50px"
      class="group-dialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTableRef"
          :data="productData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          row-key="skuId"
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            v-if="!visitDetail"
            type="selection"
            :reserve-selection="true"
            width="55"
          />
          <el-table-column label="商品信息" width="200" align="center">
            <template #default="scope">
              <img height="80" width="80" :src="scope.row.image" alt srcset />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="" />
          <el-table-column
            prop="originalPrice"
            label="原价（元）"
            width="120"
          />
          <el-table-column prop="value" label="规格" width="120" />
          <el-table-column prop="workPrice" label="拼团价（元）" width="153">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.workPrice"
                :disabled="visitDetail"
                size="small"
                :controls="false"
                :max="10000000"
                :min="0.01"
                :precision="2"
                @change="changeInput(scope.row)"
              />
              <!-- <el-input v-model="scope.row.workPrice" size="small" type="number" oninput="value=value.replace(/-/, '')" /> -->
            </template>
          </el-table-column>
          <el-table-column
            prop="stockNumber"
            label="库存"
            width="120"
            show-overflow-tooltip
          />
          <!--          <el-table-column width="80" label="操作" show-overflow-tooltip>-->
          <!--            <template #default="scope">-->
          <!--              <div class="btnList">-->
          <!--                <el-popconfirm title="确定删除此券？" @onConfirm="delGroupBuyFn(scope.row)">-->
          <!--                  <el-button slot="reference" class="delCls" type="text">删除</el-button>-->
          <!--                </el-popconfirm>-->
          <!--              </div>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="productQuery.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="productQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <div class="footBtnBox">
          <span class="dialog-footer">
            <el-button
              v-if="!visitDetail"
              type="primary"
              @click="saveIdList"
            >确 定</el-button>
            <el-button @click="closeSelect">取 消</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import {
  addGroupBuy,
  getGroupButPro,
  groupUpdate,
  groupDetail,
} from '@/api/marketing'
import { defineComponent, ref } from 'vue'

defineComponent({
  name: 'GroupForm'
})

const emit = defineEmits(['reset'])

defineExpose({
  open, close
})

function initGroupForm (data) {
  return {
    shopGroupWorkId: data && data.shopGroupWorkId || null,
    groupName: data && data.groupName || '',
    details: data && data.details || [],
    effectiveTime: data && data.effectiveTime || null,
    ifEnable: data && data.ifEnable || 1,
    enableTime: data && data.enableTime || null,
    ifAdd: data && data.ifAdd || 1,
    ifLimit: data && data.ifLimit || 1,
    limitNumber: data && data.limitNumber || null,
    person: data && data.person || null,
    startTime: data && data.startTime || '',
    endTime: data && data.endTime || '',
    remark: data && data.remark || '',
  }
}
const visible = ref(false)
const productVisible = ref(false)
const visitDetail = ref(false)
const formRef = ref()
const form = ref(initGroupForm())
const dateInfo = ref([])
const inputGroupTableData = ref([])
const multipleTableRef = ref()
const productData = ref([])
const multipleSelection = ref([])
const productQuery = ref({
  activityId: '',
  page: 1,
  pageSize: 10,
})
const total = ref(0)

const rules = {
  groupName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
  ],
  activityDate: [
    { required: true, validator: validDate, trigger: 'change' },
  ],
  person: [
    { required: true, validator: validPerson, trigger: 'blur' },
  ],
  effectiveTime: [
    { required: true, message: '请输入成团有效时间', trigger: 'blur' },
  ],
  ifLimit: [
    { validator: validLimit, trigger: 'change' },
  ],
  ifEnable: [
    { validator: validEnable, trigger: 'change' },
  ],
  commodity: [
    { required: true, validator: validCommodity, trigger: 'change' },
  ]
}
function validPerson (rule, value, callback) {
  if (!form.value.person) {
    return callback(new Error('请输入成团人数'))
  }
  if (form.value.person < 2 || form.value.person > 10) {
    return callback(new Error('拼团人数只能在2~10人之间 ！'))
  }
  callback()
}
function validDate (rule, value, callback) {
  if (!dateInfo.value || !dateInfo.value.length) {
    return callback(new Error('请选择活动时间'))
  }
  callback()
}
function validCommodity (rule, value, callback) {
  if (!form.value.details || !form.value.details.length) {
    return callback(new Error('请选择活动商品'))
  }
  callback()
}
function validLimit (rule, value, callback) {
  if (form.value.ifLimit === 2 && !form.value.limitNumber) {
    return callback(new Error('请填写商品限购数量'))
  }
  callback()
}
function validEnable (rule, value, callback) {
  console.log(value)
  if (form.value.ifEnable === 2 && !form.value.enableTime) {
    return callback(new Error('请填写活动预热时间'))
  }
  callback()
}

function vildateForm (str) {
  if (str) {
    formRef.value.validateField(str)
  }
}

function open (id, isDetail) {
  form.value.shopGroupWorkId = id
  visitDetail.value = isDetail
  if (id) {
    getGroupBuyInfo()
  }
  visible.value = true
}
function close () {
  visible.value = false
  form.value = initGroupForm()
  productQuery.value.page = 1
  dateInfo.value = []
  inputGroupTableData.value = []
  multipleTableRef.value?.clearSelection()
  formRef.value?.resetFields()
}

function changeInput (data) {
  const index = inputGroupTableData.value.findIndex(
    (item) => item.skuId === data.skuId
  )
  if (index === -1) {
    inputGroupTableData.value.push(data)
  } else {
    inputGroupTableData.value[index].workPrice = data.workPrice
  }
}

function getProList () {
  getGroupButPro(productQuery.value).then((res) => {
    if (res.code === '') {
      const dataList = res.data.list
      if (inputGroupTableData.value.length > 0) {
        dataList.forEach((item) => {
          const index = inputGroupTableData.value.findIndex(
            (cItem) => cItem.skuId === item.skuId
          )
          if (index !== -1) {
            item.workPrice = inputGroupTableData.value[index].workPrice
          }
        })
      }
      productData.value = dataList
      total.value = res.data.total
      // 点击编辑时回显表格勾选
      /*     if (multipleTableRef.value) {
            for (let i = 0; i < this.tableData.length; i++) {
              for (let j = 0; j < form.value.details.length; j++) {
                if (this.tableData[i].productId === form.value.details[j].productId && this.tableData[i].skuId === form.value.details[j].skuId) {
                  multipleTableRef.value.toggleRowSelection(this.tableData[i]);
                }
              }
            }
          } */
    }
  })
}
function handleSizeChange (val) {
  productQuery.value.pageSize = val
  getProList()
}
function handleCurrentChange (val) {
  productQuery.value.page = val
  getProList()
}
// 选择商品
function chooseProduct (type) {
  productVisible.value = true
  productQuery.value.activityId = visitDetail.value ? form.value.shopGroupWorkId : null;
  getProList()
}

/**
 * 选中
 */
// 选中商品
function handleSelectionChange (val) {
  multipleSelection.value = val
}
// 保存选择商品ID
function saveIdList () {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择商品')
    return
  }
  try {
    const idList = []
    multipleSelection.value.forEach((item) => {
      if (!item.workPrice) {
        ElMessage.warning('请输入价格')
        throw new Error()
      }
      idList.push({
        price: item.workPrice,
        productId: item.productId,
        skuId: item.skuId,
      })
    })
    form.value.details = idList
    vildateForm('commodity');
    productVisible.value = false
  } catch (e) {
    console.log(e)
  }
}
// 取消选择
function closeSelect () {
  productVisible.value = false
}
// 跳转秒杀列表
function goToGroupBuy () {
  emit('reset')
}

function getGroupBuyInfo () {
  groupDetail({
    shopGroupWorkId: form.value.shopGroupWorkId
  }).then(res => {
    form.value = initGroupForm(res.data)

    form.value.effectiveDay = res.data.effectiveDay
    form.value.frequency = res.data.frequency
    form.value.groupBuyContent = res.data.groupBuyContent
    const idList = res.data.products
    idList.forEach((i) => {
      form.value.details.push({
        price: i.workPrice || i.originalPrice,
        productId: i.productId,
        skuId: i.skuId,
      })
    })
    dateInfo.value = [form.value.startTime, form.value.endTime]
  })
}

function addGroupBuyFn () {
  formRef.value.validate((valid) => {
    if (valid) {
      form.value.startTime = dateInfo.value[0]
      form.value.endTime = dateInfo.value[1]

      if (form.value.shopGroupWorkId) {
        groupUpdate(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('修改成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      } else {
        addGroupBuy(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('提交成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      }
    }
  })
}

</script>

<style lang="scss" scoped>
.addGroupBuy {
  background: #ffffff;
  .dialog-footer {
    display: flex;
    justify-content: center;
    .el-button {
      margin: 0px 16px;
    }
  }
  .formBox {
    margin-top: 20px;
    .applyType {
      span {
        display: inline-block;
        width: 100px;
        height: 30px;
        line-height: 30px;
        margin-right: 30px;
        border-radius: 4px;
        background: #66b1ff;
        color: #ffffff;
        text-align: center;
        font-size: 14px;
        cursor: pointer;
        position: relative;
        i {
          position: absolute;
          right: -10px;
          top: -10px;
          width: 25px;
          height: 25px;
          line-height: 25px;
          background: #ffffff;
          border-radius: 50%;
          border: 1px solid #66b1ff;
          text-align: center;
          color: #3A68F2;
          font-style: normal;
          font-size: 12px;
        }
      }
    }
  }
  .footBtnBox {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
  .dateBox {
    display: flex;
    align-items: center;
    .description {
      width: 59px;
      text-align: center;
      display: block;
      font-size: 14px;
      color: #999999;
    }
  }
}
</style>